package com.ruoyi.common.filter;

import com.ruoyi.common.filter.path.AntPathMatcherSingleton;
import com.ruoyi.common.filter.path.PathMatcher;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public abstract class AbstractResourceFilter implements Filter {

    /**
     * 路径匹配器
     */
    private PathMatcher pathMatcher;

    /**
     * 排除路径
     */
    private Set<String> excludes = new HashSet<>();

    public AbstractResourceFilter() {
        this.pathMatcher = AntPathMatcherSingleton.PATH_MATCHER.getPathMatcher();
    }

    public AbstractResourceFilter(String exclude) {

        if (StringUtils.isNotBlank(exclude)) {
            this.excludes.addAll(Arrays.asList(exclude.split(",")));
        }
    }

    public AbstractResourceFilter appendExcludesUrl(String url) {
        this.excludes.add(url);

        return this;
    }

    /**
     * 当前请求是否在排除路径当中
     * 使用ant格式的路径匹配器
     *
     * @param path 请求路径
     * @return true or false
     */
    protected boolean isInExcludes(String path) {
        if (excludes == null || excludes.isEmpty()) {
            return false;
        }
        for (String exclude : excludes) {
            if (pathMatcher.match(exclude, path)) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Set<String> excludes = new HashSet<>();
        excludes.add("/**/*swagger*/**");

        boolean isInExclude = false;
        for (String exclude : excludes) {
            if (AntPathMatcherSingleton.PATH_MATCHER.getPathMatcher().match(exclude, "/swagger-ui.html")) {
                isInExclude =true;
            }
        }

        System.out.println(isInExclude);

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

}
